import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index.js'

// import Login from '@/views/Login/index.vue'
// import Login from '../views/Login/index.vue'
const Login = () => import('../views/Login/index.vue')
// import Main from '../views/Main/index.vue'
const Main = () => import('../views/Main/index.vue')
// import Home from '../views/Home/index.vue'
const Home = () => import('../views/Home/index.vue')
// import User from '../views/User/index.vue'
const User = () => import('../views/User/index.vue')
// import Search from '../views/Search/Search.vue'
const Search = () => import('../views/Search/Search.vue')
// 导入搜索结果页
// import SearchResult from '../views/SearchResult/SearchResult.vue'
const SearchResult = () => import('../views/SearchResult/SearchResult.vue')
// 导入文章详情组件
// import ArticleDetail from '../views/ArticleDetail/ArticleDetail.vue'
const ArticleDetail = () => import('../views/ArticleDetail/ArticleDetail.vue')
// 导入 UserEdit.vue 组件
// import UserEdit from '../views/UserEdit/UserEdit.vue'
const UserEdit = () => import('../views/UserEdit/UserEdit.vue')
// 导入小思同学的组件页面
// import Chat from '../views/Chat/Chat'
const Chat = () => import('../views/Chat/Chat')
Vue.use(VueRouter)

// 解决 vue-router 内部的报错的问题：
// 1. 将 VueRouter 本身提供的 $router.push 方法转存到常量中
const originalPush = VueRouter.prototype.push
// 2. 自定义 $router.push 方法，在内部调用原生的 originalPush 方法进行路由跳转；并通过 .catch 捕获错误
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  // 通过 .catch 捕获错误
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/login',
    component: Login,
    name: 'login'
  },
  {
    path: '/',
    component: Main,
    // 为什么要删除还有子路由的父路由名字
    // 含有子路由的路由 有默认的路由， 不能加命名路由
    // name: 'main',
    children: [
      // path 为"空字符串"的子路由规则，叫做"默认子路由"
      {
        path: '',
        component: Home,
        name: 'home',
        meta: { isRecord: true, top: 0 }
      },
      {
        path: '/user',
        component: User,
        name: 'user'
      },
      {
        path: '/search',
        component: Search,
        name: 'search'
      },
      // 搜索结果页
      { path: '/search/:kw', component: SearchResult, name: 'search-result', props: true, meta: { isRecord: true, top: 0 } }

    ]
  },
  // 文章详情的路由规则
  { path: '/article/:id', component: ArticleDetail, name: 'article-detail', props: true, meta: { isRecord: true, top: 0 } },
  // 编辑用户资料的路由规则
  { path: '/user/edit', component: UserEdit, name: 'user-edit' },
  // 小思聊天的路由规则
  { path: '/chat', component: Chat, name: 'chat' }
]

const router = new VueRouter({
  routes
})

// 所有有权限页面的路径，都在这个数组之中
const pagePathArr = ['/user', '/user/edit']
// 为路由的实例对象挂载全局前置守卫
router.beforeEach((to, from, next) => {
  // 访问的是有权限的页面，需要判断用户是否登录
  if (pagePathArr.indexOf(to.path) !== -1) {
    // 1. 从 store 中获取 token 的值
    //    注意：store.state.tokenInfo 要么是 {} 空对象，要么是包含 {token, refresh_token} 的对象
    const tokenStr = store.state.tokenInfo.token
    // console.log(tokenStr)
    if (tokenStr) {
      // 1.1 token 有值，已登录过（操作：直接放行）
      next()
    } else {
      // 1.2 token 不存在，没有登录（操作：强制跳转到登录页）
      // next('/login')
      next(`/login?url=${to.fullPath}`)
    }
  } else {
    // 访问的是没有权限的页面
    next()
  }
})

// 全局后置钩子
router.afterEach((to, from) => {
  // 如果当前的路由的元信息中，isRecord 的值为 true
  if (to.meta.isRecord) {
    setTimeout(() => {
      window.scrollTo(0, to.meta.top)
    }, 0)
  }
})

export default router
